<template>
  <div class="patient-container">
    <h1>绑定患者</h1>
    <!-- 检查用户信息是否加载完成 -->
    <div v-if="userInfo" style="width: 90%;align-content: center;">
      <el-form :model="userInfo" label-width="100px">
        <el-form-item label="患者Id">
          <el-input v-model="userInfo.patient.patientId" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="userInfo.patient.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者年龄">
          <el-input v-model="userInfo.patient.age" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者性别">
          <el-input v-model="userInfo.patient.sex" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者联系电话">
          <el-input v-model="userInfo.patient.contactNumber" disabled></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="showEditDialog">编辑</el-button>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">添加新患者</el-button>
    </div>
    <div v-else>
      加载中...
    </div>
    <!-- 编辑用户信息对话框 -->
    <el-dialog v-model="dialogFormVisible" title="编辑患者信息" width="500">
      <el-form :model="editUser.patient" :rules="rules" ref="formRef" label-position="right" label-width="auto">
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="editUser.patient.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model.number="editUser.patient.age" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者性别" prop="sex">
          <el-input v-model="editUser.patient.sex" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者联系电话" prop="contactNumber">
          <el-input v-model="editUser.patient.contactNumber" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">修改</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加新数据对话框 -->
    <!-- 模态框 -->
    <el-dialog v-model="dialogFormVisible2" title="言㐱陪诊" width="500">
      <el-form :model="form" :rules="rules2" ref="formRef" label-position="right" label-width="auto">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input v-model="form.sex" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取消</el-button>
          <el-button v-if="!isEdit2" type="primary" @click="handleAdd2">新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ElMessage} from 'element-plus';
import axios from 'axios';
import {mapGetters} from 'vuex';
import {Plus} from "@element-plus/icons-vue";

export default {
  computed: {
    Plus() {
      return Plus
    },
    ...mapGetters(['getUserId']) // 假设 Vuex 中存储的是 patient_id
  },
  data() {
    return {
      dialogFormVisible2: false,
      isEdit2: false,
      userInfo: {
        user_id: null,
        username: '',
        patient: {
          patientId: null,
          name: '',
          age: null,
          sex: '',
          contactNumber: ''
        }
      },
      dialogFormVisible: false,
      editUser: {
        user_id: null,
        username: '',
        patient: {
          patientId: null,
          name: '',
          age: null,
          sex: '',
          contactNumber: ''
        }
      },
      rules: {
        'patient.name': [
          {required: true, message: '请输入患者姓名', trigger: 'blur'}
        ],
        'patient.age': [
          {required: true, message: '请输入患者年龄', trigger: 'blur'},
          {type: 'number', message: '患者年龄必须为数字值', trigger: 'blur'}
        ],
        'patient.sex': [
          {required: true, message: '请输入患者性别', trigger: 'blur'}
        ],
        'patient.contactNumber': [
          {required: true, message: '请输入患者联系电话', trigger: 'blur'}
        ]
      },
      form: {
        name: '',
        age: 0,
        sex: '',
        contactNumber: '',
      },
      rules2: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {type: 'number', message: '年龄必须为数字值', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请输入性别', trigger: 'blur'}
        ],
        contactNumber: [
          {required: true, message: '请输入联系电话', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.setPatientInfo();
    // this.getPatientInfo();
  },
  methods: {
    async setPatientInfo() {
      const UserId = this.getUserId;
      if (UserId) {
        try {
          const res = await axios.get(`/api/wu_vue_2_test/Patient/getByUserId?UserId=${UserId}`);
          if (res.data.code === 200) {
            this.userInfo.patient = res.data.data;
            this.editUser.patient = {...this.userInfo.patient};
          } else {
            ElMessage.error(res.data.message);
          }
        } catch (error) {
          console.error('请求出错:', error);
          ElMessage.error('请求出错，请稍后重试');
        }
      } else {
        ElMessage.error('未获取到本次登录信息，请检查');
      }
    },
    showEditDialog() {
      this.dialogFormVisible = true;
      this.editUser.patient = {...this.userInfo.patient};
    },
    async handleEdit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post('/api/wu_vue_2_test/Patient/update', this.editUser.patient);
            if (res.data.code === 200) {
              this.userInfo.patient = {...this.editUser.patient};
              this.dialogFormVisible = false;
              ElMessage.success('修改成功');
            } else {
              ElMessage.error(res.data.message);
            }
          } catch (error) {
            console.error('修改数据失败:', error);
            ElMessage.error('修改数据失败，请稍后重试');
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    },

    // 2. 添加新数据
    async handleAdd2() {
      console.log(this.form);
      const res = await axios.post('/api/wu_vue_2_test/Patient/add2', this.form);
      console.log(this.form);
      console.log(res);
      this.dialogFormVisible2 = false;
      if (res.data.code === 200) {
        this.userInfo.patient = {...this.editUser.patient};
        this.dialogFormVisible = false;
        const newPatientId = res.data.data;
        alert(`
        新患者的患者ID: ${newPatientId}
        想要修改到用户信息中请在个人中心修改患者ID
        `);
        this.showMsg(res);
      } else {
        ElMessage.error(res.data.message);
      }
    },
    // 显示添加新数据对话框
    showAddDialog() {
      this.isEdit2 = false;
      this.dialogFormVisible2 = true;
      this.resetForm();
    },
    // 重置表单
    resetForm() {
      this.form = {
        name: '',
        age: 0,
        sex: '',
        contactNumber: ''
      };
    },
    // 显示操作结果消息
    showMsg(res) {
      if (res.data.code === 200) {
        ElMessage({
          message: res.data.msg,
          type: 'success',
          plain: true
        });
      } else {
        ElMessage({
          message: res.data.msg,
          type: 'error',
          plain: true
        });
      }
    }
  }
};
</script>

<style scoped>
.patient-container {
  padding: 20px;
}
</style>